import { StrictMode } from "react";
import { createRoot } from "react-dom/client";

import App from "./App.jsx";

import {
    renderWithQiankun,
    qiankunWindow,
} from "vite-plugin-qiankun/dist/helper";

import { setShareMainComponent } from "@/utils/share-main.js";

let instance = null;

/**
 * 渲染函数
 * 两种情况：主应用生命周期钩子中运行 / 微应用单独启动时运行
 * (在住应用中运行时，document会被主应用的document覆盖)
 */
function renderReact(props) {
    // 挂载应用
    console.log(">>> sub-react render");
    const { container } = props;
    instance = createRoot(
        container
            ? container.querySelector("#react-app")
            : document.getElementById("react-app")
    );
    instance.render(
        <StrictMode>
            <App />
        </StrictMode>
    );
}
renderWithQiankun({
    mount(props) {
        const {
            onGlobalStateChange,
            setGlobalState,
            shareReactComponent,
            reactDoc,
            enums,
            name,
        } = props;
        console.log(">>> sub-react mount");

        setShareMainComponent(shareReactComponent);
        renderReact(props);
    },
    bootstrap() {
        console.log(">>> sub-react bootstrap");
    },
    unmount(props) {
        console.log(">>> sub-react unmounted");
        instance.unmount();
        instance = null;
    },
});

// 独立运行时，直接挂载应用
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
    renderReact({});
    console.log(">>> sub-react run alone");
}
